package top.hjcwzx.wrench.mqtt.strategy.impl;

import top.hjcwzx.wrench.mqtt.event.MqttMessageEvent;
import top.hjcwzx.wrench.mqtt.service.publish.MqttEventPublisher;
import top.hjcwzx.wrench.mqtt.strategy.MqttMessageHandler;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


public class MixedStrategy implements MqttMessageHandler {

    private final MqttEventPublisher publisher;

    public MixedStrategy(MqttEventPublisher publisher) {
        this.publisher = publisher;
    }

    @Override
    public void handleMessage(String topic, String payload, Map<String, List<Consumer<Object>>> topicHandlerMap) {

        //区分获取基于注解式注册的主题/通过配置文件注册的主题,防止重复调用
        List<Consumer<Object>> annotationMqttSubscribeConsumer = topicHandlerMap.getOrDefault(topic, Collections.emptyList());
        if(!annotationMqttSubscribeConsumer.isEmpty()){
            annotationMqttSubscribeConsumer.forEach(handler -> handler.accept(payload));
        }else {
            publisher.publish(new MqttMessageEvent(this, topic, payload));
        }
    }
}
